package marchsoft.modules.selfFish.pisciculture.service.impl;
/**
 * @title EquipmentServiceImpl
 * @description
 * @author Lenovo
 * @version 1.0
 * @create 2024-07-15 17:28
 */

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.selfFish.pisciculture.entity.Equipment;
import marchsoft.modules.selfFish.pisciculture.entity.dto.EquipmentDto;
import marchsoft.modules.selfFish.pisciculture.entity.vo.EquipmentVo;
import marchsoft.modules.selfFish.pisciculture.mapper.EquipmentMapper;
import marchsoft.modules.selfFish.pisciculture.service.EquipmentService;
import marchsoft.modules.system.entity.SysRelationFile;
import marchsoft.modules.system.service.ISysRelationFileService;
import marchsoft.response.Result;
import marchsoft.utils.FileUtils;
import marchsoft.utils.SecurityUtils;
import marchsoft.utils.ServiceType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 *@title EquipmentServiceImpl
 *@description
 *@author Lenovo
 *@version 1.0
 *@create 2024-07-15 17:28
 */
@Service
@Slf4j
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment>implements EquipmentService {

    @Autowired
    private  EquipmentMapper equipmentMapper;

    @Autowired
    private  EquipmentService equipmentService;

    @Autowired
    private ISysRelationFileService sysRelationFileService;

    @Override
    public Result<Object> getEquipmentList(String equipmentName, Long pageNum, Long pageSize) {
        IPage<EquipmentVo> equipmentList = equipmentMapper.getEquipmentList(new Page<>(pageNum, pageSize), equipmentName);
        equipmentList.getRecords().forEach(healthVo -> {
            QueryWrapper<SysRelationFile> qw = new QueryWrapper<>();
            qw.eq("service_id",healthVo.getId())
            .eq("status","1")
            .eq("service_type", ServiceType.EQUIPMENT);;
            List<SysRelationFile> list = sysRelationFileService.list(qw);
            if(list != null && list.size()>0){
                healthVo.setFileId(list.get(0).getId());
            }

        });
        return Result.success(equipmentList);
    }

    @Override
    public Result<Object> create(EquipmentDto equipmentDto) {
        Equipment equipment = new Equipment();
        BeanUtils.copyProperties(equipmentDto,equipment);
        equipment.setCreatedUserId(SecurityUtils.getCurrentUserId());
        equipment.setCreatedTime(LocalDateTime.now());
        equipment.setStatus(true);
        if(equipmentMapper.insert(equipment)>0){
            //附件保存
            sysRelationFileService.saveFile(equipmentDto.getFileId(),equipment.getId(),ServiceType.EQUIPMENT);
            log.info(StrUtil.format("【添加设备成功】操作人id：{}，新增目标equipment：{}", SecurityUtils.getCurrentUserId(), equipmentDto));
            return Result.success("新增成功！");
        };
        return Result.error("新增失败！");
    }

    @Override
    public Result<Object> delete(Set<Long> ids) {
        UpdateWrapper<Equipment>uw = new UpdateWrapper<>();
        uw.in("id",ids)
                .set("status",false);
        if(equipmentService.update(uw)){
            //删除附件
            sysRelationFileService.deleteFile(new ArrayList<>(ids),ServiceType.EQUIPMENT);
            log.info(StrUtil.format("【删除设备成功】操作人id：{}，删除目标equipments：{}", SecurityUtils.getCurrentUserId(), ids.toString()));
            return Result.success("删除成功！");
        };
        return Result.error("删除失败！");
    }

    @Override
    public Result<Object> update(EquipmentDto equipmentDto) {
        Equipment equipment = getById(equipmentDto.getId());
        if (ObjectUtil.isEmpty(equipment)) {
            log.error(StrUtil.format("【修改设备失败】操作人id：{}，修改目标equipment为空，目标equipmentId：{}", SecurityUtils.getCurrentUserId(), equipment.getId()));
            throw new BadRequestException("修改失败，当前数据id不存在");
        }
        if(equipment.getCreatedUserId()!=SecurityUtils.getCurrentUserId()){
            log.error(StrUtil.format("【修改设备失败】操作人id：{}，目标equipment新增人id：{}", SecurityUtils.getCurrentUserId(), equipment.getCreatedUserId()));
            throw new BadRequestException("该设备不是你新增的，不能修改：" + equipment.getZhName());
        }
        BeanUtils.copyProperties(equipmentDto,equipment);
        if(updateById(equipment)){
            //先删除
            sysRelationFileService.deleteFile(Arrays.asList(equipmentDto.getId()),ServiceType.EQUIPMENT);
            //附件保存
            sysRelationFileService.saveFile(equipmentDto.getFileId(),equipment.getId(),ServiceType.EQUIPMENT);
            log.info(StrUtil.format("【修改设备成功】操作人id：{}，修改目标equipment：{}", SecurityUtils.getCurrentUserId(), equipmentDto));
            return Result.success("修改成功！");
        };
        return Result.error("修改失败！");
    }

    @Override
    public void download(String equipmentName, HttpServletResponse response) throws IOException {
        Page<Equipment> page = new Page<>(-1, -1);
        List<EquipmentVo> records = equipmentMapper.getEquipmentList(page, equipmentName).getRecords();
        List<Map<String, Object>> list = new ArrayList<>();
        records.forEach(equipmentVo -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号", equipmentVo.getRowNum());
            map.put("设备名称", equipmentVo.getZhName());
            map.put("设备类型", equipmentVo.getEquipTypeName());
            map.put("数量", equipmentVo.getNum());
            map.put("金额", equipmentVo.getPrice());
            map.put("描述", equipmentVo.getDescription());
            map.put("创建时间", LocalDateTimeUtil.format(equipmentVo.getCreatedTime(),DatePattern.NORM_DATETIME_FORMATTER));
            list.add(map);
        });
        //设置宽度
        Map<Integer, Integer>widthMap = new HashMap<>();
        widthMap.put(0, 6);
        widthMap.put(1, 15);
        widthMap.put(2, 15);
        widthMap.put(3, 15);
        widthMap.put(4, 15);
        widthMap.put(5, 45);
        widthMap.put(6, 30);
        FileUtils.downloadExcel(list,widthMap, response);
    }
}
